package com.fyt.reachgo.consummer;

import com.fyt.reachgo.config.RabbitMQConfig;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.fyt.reachgo.utils.RedisConstants.GET_TRAVEL_REQ_BY_USERS_KEY;
import static com.fyt.reachgo.utils.RedisConstants.GET_TRAVEL_REQ_BY_USER_KEY;

@Component
@RequiredArgsConstructor
@Slf4j
public class TravelRequestConsumer {

    private final StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queues = RabbitMQConfig.TRAVEL_REQUEST_USER_QUEUE, concurrency = "5-10")
    public void handleTravelRequestMessage(Long userId,
                                           Channel channel,
                                           @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.info("接收到消息：{}", userId);
        try {
            // 删除用户redis缓存
            stringRedisTemplate.delete(buildUserKey(userId));
            stringRedisTemplate.delete(buildUsersKey());
            // 确认消息
            channel.basicAck(deliveryTag, false);
            log.info("[用户消息] 缓存处理成功, 用户ID: {}", userId);
        }catch (Exception e){
            log.error("[用户消息] 处理失败, 用户ID: {}", userId, e);
            // 重试
            handleTravelRequestMessage(userId,channel, deliveryTag);
        }
    }

    private String buildUserKey(Long userId) {
        return GET_TRAVEL_REQ_BY_USER_KEY + userId;
    }

    private String buildUsersKey() {
        return GET_TRAVEL_REQ_BY_USERS_KEY;
    }
}
